package cl.gob.minvu.catastromobile.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author psep
 *
 */
public final class RestService {
	
	private static final Logger logger = Logger.getLogger(RestService.class);

	/**
	 * Método que consume el servicio REST entregado
	 * mediante parámetro como String retornando el
	 * resultado en formato JSON.
	 * 
	 * @param url
	 * @return String
	 */
	public static final String GET(String url, String object) {
		InputStream inputStream = null;
		String result = "";
		
		try {
			String enconde = URLEncoder.encode(object, "UTF-8");
			String urlService = url + enconde;
			
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(urlService);
			HttpParams httpParams = httpGet.getParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
			HttpConnectionParams.setSoTimeout(httpParams, 10000);
			HttpResponse httpResponse = httpclient.execute(httpGet);
			inputStream = httpResponse.getEntity().getContent();

			if (inputStream != null){
				result = convertInputStreamToString(inputStream);
				result = GenericUtil.decode(result);
			} else {
				result = "Did not work!";
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return result;
	}
	
	public static final String POST(String url, UrlEncodedFormEntity entity) {
		InputStream inputStream = null;
		String result = "";
		
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(entity);
			
			HttpResponse httpResponse = httpclient.execute(httpPost);
			inputStream = httpResponse.getEntity().getContent();			

			if (inputStream != null){
				result = convertInputStreamToString(inputStream);
				result = GenericUtil.decode(result);
			} else {
				result = "Did not work!";
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return result;
	}

	/**
	 * Método que convierte el input de la llamada REST mediante
	 * HTTP en un String
	 * 
	 * @param inputStream
	 * @return String
	 * @throws IOException
	 */
	private static final String convertInputStreamToString(InputStream inputStream)
			throws IOException {
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream));
		String line = "";
		StringBuilder result = new StringBuilder();

		while ((line = bufferedReader.readLine()) != null) {
			result.append(line);
		}

		inputStream.close();
		return result.toString();

	}
	
	/**
	 * Método que permite identificar el mensaje de error
	 * mediante el JSON entregado.
	 * 
	 * @param json
	 * @return
	 */
	public static final String getErrorMessage(String jsonStr) {
		String message = "";
		
		try {
			JSONObject json = new JSONObject(jsonStr);
			int codigo = json.getInt("e");
			
			switch (codigo) {
			case 404:
				message = "No existe el usuario";
				break;
				
			case 111:
				message = "Los datos proporcionados no son válidos, por favor verifique";
				break;
				
			case 101:
				message = "Timeout, intente más tarde";
				break;
				
			case 300:
				message = "Su token ha expirado, solicite una ampliación de validez";
				break;
				
			case 303:
				message = "Usuario o contraseña incorrectos";
				break;
				
			case 500:
				message = "Error en el servidor, intente más tarde";
				break;

			default:
				message = "Error de conexión, intente más tarde";
				break;
			}
			
		} catch (JSONException e) {
			message = "Error de conexión, intente más tarde";
		}
		
		return message;
	}

}
